package com.heima.wemedia.service.impl;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @package com.heima.wemedia.service.impl
 * @Date 2022/3/1
 * @project heima-leadnews
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String website;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        if (multipartFile == null || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        String originalFilename = multipartFile.getOriginalFilename();
        if (!checkFile(originalFilename)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确文件格式");
        }
        //上传到OSS上
        String fileUrl = null;
        try {
            String filename = UUID.randomUUID().toString().replace("-", "");
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            fileUrl = fileStorageService.store(prefix, filename + suffix, multipartFile.getInputStream());
            log.info("fileId {}", fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        //封装数据
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(fileUrl);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        wmMaterial.setUrl(website + fileUrl);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        dto.checkParam();
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        queryWrapper.eq(WmMaterial::getUserId, user.getId());
        queryWrapper.orderByAsc(WmMaterial::getCreatedTime);
        Page<WmMaterial> pages = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> resultPage = page(pages, queryWrapper);
        List<WmMaterial> records = resultPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(website + record.getUrl());
        }
        return new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal(), records);


    }

    /**
     * 删除素材
     * @param id
     * @return
     */
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult deleteFile(Integer id) {
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = getById(id);
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(queryWrapper);
        if (wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (count>0){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        if (!user.getId().equals(wmMaterial.getUserId())){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH,"该素材不是本人上传无法删除");
        }
        removeById(id);
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short status) {
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer uid = WmThreadLocalUtils.getUser().getId();
        if (!wmMaterial.getUserId().equals(uid)){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wmMaterial.setIsCollection(status);
        updateById(wmMaterial);
        return ResponseResult.okResult();

    }

    private boolean checkFile(String originalFilename) {
        if (StringUtils.isBlank(originalFilename)) {
            return false;
        }
        List<String> allowffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        for (String s : allowffix) {
            if (originalFilename.endsWith(s)) {
                return true;
            }
        }
        return false;
    }
}
